<template>
  <div class="dialog">
    <el-select
      v-model="addrVal"
      :loading="loading"
      clearable
      remote
      filterable
      reserve-keyword
      placeholder="请输入关键词"
      :remote-method="remoteMethod"
      @change="selectChange"
      class="mapSelect"
    >
      <el-option
        v-for="item in addrList"
        :key="item.id"
        :label="item.name"
        :value="item.name + '_' + item.district"
      >
        <div class="option" style="display: flex; justify-content: space-between">
          <span>{{ item.name }}</span>
          <span style="margin-left: 20px; color: #999; font-size: 12px">{{ item.district }}</span>
        </div>
      </el-option>
    </el-select>
    <div id="container" class="mt20"></div>
  </div>
</template>
<script>
import AMapLoader from "@amap/amap-jsapi-loader";
// 安全密钥
window._AMapSecurityConfig = {
  securityJsCode: "228419df8151477cf6c50c2ce131bc89"
};
export default {
  props: {
    show: {
      type: Boolean,
      default: false
    },
    info: {
      type: Object,
      default: () => {}
    },
    autoCompleteCity: {
      type: String,
      default: "全国"
    }
  },
  data() {
    return {
      visible: false,
      loading: false,
      addrVal: "",
      currentAddr: {},
      addrList: [],
      mapEl: null,
      aMap: null,
      geolocation: null,
      autoComplete: null,
      marker: null
    };
  },
  watch: {
    show(n) {
      this.visible = n;
      if (n) {
        this.$nextTick(() => {
          this.initMap();
        });
      }
    },
    info(n) {
      this.currentAddr = n;
    }
  },
  methods: {
    initMap() {
      AMapLoader.reset();
      AMapLoader.load({
        key: "4714b27b49d825e47a442a0d76a9c95d", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺少时默认为 1.4.15
        plugins: [
          "AMap.AutoComplete",
          "AMap.Marker",
          "AMap.PlaceSearch",
          "AMap.Geolocation"
        ] // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      }).then(AMap => {
        this.aMap = AMap;
        // 设置地图容器id
        this.mapEl = new AMap.Map("container", {
          viewMode: "3D", // 是否为3D地图模式
          zoom: 10, // 初始化地图级别
          center: [116.397428, 39.90923] // 初始化地图中心点位置  默认当前行政区
        });

        this.geolocation = new AMap.Geolocation({
          enableHighAccuracy: true, // 是否使用高精度定位，默认:true
          timeout: 1000, // 超过10秒后停止定位，默认：5s
          showButton: true, // 显示定位按钮，默认：true
          position: "RB", // 定位按钮的停靠位置
          offset: [10, 20], // 定位按钮与设置的停靠位置的偏移量，默认：[10, 20]
          showMarker: true, // 定位成功后在定位到的位置显示点标记，默认：true
          panToLocation: true, // 定位成功后将定位到的位置作为地图中心点，默认：true
          zoomToAccuracy: true // 定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
        });
        // this.mapEl.addControl(this.geolocation)
        // this.geolocation.getCurrentPosition() // 自动获取定位
        // // 返回定位信息
        // this.geolocation.on('complete', (res) => {
        //   console.log('res', res)
        // })
        // // 返回定位出错信息
        // this.geolocation.on('error', (err) => {
        //   console.log('err', err)
        // })
        // this.getCurrentAddr();
        this.autoComplete = new AMap.AutoComplete({
          city: this.autoCompleteCity
        });
        if (this.info.lng && this.info.lat) {
          this.addmark(this.currentAddr);
        }
        this.mapEl.on("click", e => {
          // this.getAddress(e.lnglat.getLng(), e.lnglat.getLat());
        });
      });
    },
    // 获取当前位置
    getCurrentAddr() {
      this.geolocation.getCurrentPosition((status, result) => {
        console.log(status, result, "aaaaaaaaaaaaaaaaaaaaa");
        if (status == "complete") {
          this.getAddress(result.position.lng, result.position.lat);
          return result.position;
        } else {
          this.$message.error("获取定位失败");
        }
      });
    },
    // 地址逆解析
    getAddress(lng, lat) {
      fetch(
        `https://restapi.amap.com/v3/geocode/regeo?location=${lng},${lat}&key=da013c1936bc092b59425cd1004f5571&radius=1000&extensions=all`,
        {
          method: "get"
        }
      )
        .then(res => {
          console.log("res", res);

          return res.text();
        })
        .then(res => {
          res = JSON.parse(res);
          console.log(res, "res");
          if (res.status == "1") {
            this.addmark({ lng, lat, name: res.regeocode.formatted_address });
          } else {
            this.$message({ message: res.info, type: "error" });
          }
        });
    },
    addmark(info) {
      if (this.marker) this.mapEl.remove(this.marker);
      this.currentAddr = info;
      this.marker = new this.aMap.Marker({
        position: new this.aMap.LngLat(info.lng, info.lat),
        title: info.name, // 鼠标滑过点标记时的文字提示
        label: {
          content: info.name // 文本标注的内容
        }
        // zooms: 14 // 点标记显示的层级范围，超过范围不显示。默认值：zooms: [2, 20]
      });
      this.mapEl.add(this.marker);
      this.mapEl.setCenter([info.lng, info.lat], false, 500); // 中心点 是否直接迁移(动画过度) 过渡时间
    },
    // 自定义远程搜索方法
    remoteMethod(e) {
      if (e.trim() != "") {
        this.loading = true;
        setTimeout(() => {
          this.autoComplete.search(e, (status, result) => {
            // console.log(status, result)
            this.loading = false;
            if (status == "complete" && result.tips.length) {
              this.addrList = result.tips;
            }
          });
        }, 200);
      }
    },
    selectChange(e) {
      if (!e) return;
      let info = this.addrList.find(v => v.name + "_" + v.district == e);
      if (info.location) {
        // 自动适应显示想显示的范围区域
        // this.mapEl.setFitView()
        this.addmark({
          ...info.location,
          name: info.name,
          address: info.address
        });
        this.$emit("confirm", this.currentAddr);
      } else {
        this.$message.warning("该地点经纬度信息缺失");
      }
    },
    cancel() {
      this.visible = false;
      this.$emit("cancel", false);
    },
    confirm() {
      if (!this.currentAddr.name) {
        this.$message.warning("请先选择一个地址");
        return;
      }
      this.cancel();
      this.$emit("confirm", this.currentAddr);
    }
  }
};
</script>

<style lang="scss" scoped>
.dialog {
  border-radius: 4px;
  background-color: #ffffff;
  .map-head {
    height: 40px;
    width: 100%;
    display: flex;
    align-items: center;
    .currentAddr {
      margin-left: 32px;
    }
  }

  #container {
    height: 450px;
    width: 700px;
    margin-top: 10px;
    position: relative;
  }
  .mapSelect {
    z-index: 99;
    .el-input__inner {
      width: 100% !important;
    }
  }
}
</style>
